package za.org.jcicada.comms.impl.inprocess;

import java.io.IOException;
import java.net.URI;

import za.org.jcicada.comms.IAcceptListener;
import za.org.jcicada.comms.impl.AcceptorBase;
import za.org.jcicada.comms.impl.ConnectorFactory;

/**
 * In Process implementation of the IAcceptor interface. Client connections
 * connect by calling connect directly on this acceptor.
 */
public class InProcessAcceptor extends AcceptorBase {
    
    private boolean closed = false;
    
    public static final String IN_PROCESS = "inprocess";

    public InProcessAcceptor(IAcceptListener acceptListener) {
        super(acceptListener);
        ConnectorFactory.registerInProcessAcceptor(this);
    }

    /**
     * This serves the same purpose as a TCP connect request, ie it informs the
     * acceptor that the client wishes to connect. It then establishes the local
     * connection to handle both ends of the connection.
     * 
     * @param clientConnection the client's connection
     */
    public void connect(InProcessConnection clientConnection) throws IOException {
        if (null == clientConnection) {
            throw new IllegalArgumentException("clientConnection may not be null");
        }

        if (closed) {
            throw new IOException("Trying to connect to closed acceptor");
        } else {
            InProcessConnection connection = new InProcessConnection(clientConnection);
            addQueue(connection);
        }
    }

    @Override
    public void close() throws IOException {
        closed = true;
        super.close();
    }
    
    @Override
    public boolean isClosed() {
    	return closed;
    }
    
    @Override
    public String getProtocol() {
        return IN_PROCESS;
    }

    @Override
    public URI getBaseLocationURI() {
        return URI.create(String.format("%s://local:%d", getProtocol(), hashCode()));
    }

}
